#include <iostream>
#include <thread>
#include <cstring>
#include <string>
#include <sstream>
#include <map>
#include <mysql/mysql.h>
using namespace std;

int main(){

    MYSQL mysql;
    mysql_init(&mysql);
    const char* host = "127.0.0.1";
    const char* user = "root";
    const char* pass = "123456";
    const char* db = "laoxiaoketang";

    //连接超时
    int to = 3;
    int re = mysql_options(&mysql,MYSQL_OPT_CONNECT_TIMEOUT,&to);
    if(re != 0){
        std::cerr<<"mysql_options failed!"<<mysql_error(&mysql)<<std::endl;
    }

    //自动重连
    int reconnect = 3;
    mysql_options(&mysql,MYSQL_OPT_RECONNECT,&reconnect);

    //连接（阻塞的）
    if(!mysql_real_connect(&mysql,host,user,pass,db,3306,0,CLIENT_MULTI_STATEMENTS)){
        std::cerr<<"mysql connect failed!"<<mysql_error(&mysql)<<std::endl;
    }else{
        std::cout<<"mysql connect "<<host<<" success!"<<std::endl;
    }

    std::string sql = "";

    //1.创建表
    sql =R"(CREATE tABLE IF NOT EXISTS `t_image`(
        `id` int AUTO_INCREMENT,
        `name` varchar(1024),
        `path` varchar(1024),
        `size` int,
        PRIMARY KEY(`id`)
    );)";

    sql +=  R"(truncate t_image;)";

    int count = 0;

for(int i=0;i<100;i++){
    //2.插入数据
    //sql = R"(insert `t_image` (`name`,`path`,`size`) values('test.jpg','/mnt/data',10240))";
    stringstream ss;
    ss << R"(insert `t_image` (`name`,`path`,`size`) values('image_)";
    ss <<i<< R"(.jpg','/mnt/data',10240);)";
    sql += ss.str();
}

    //3.修改数据
    sql += R"(update t_image set `name` = "test3.png",`size`="4000" where id = 2;)";

    //4.删除数据
    sql += R"(delete from t_image where id =1;)";

    sql += R"(select * from t_image;)";

    //执行语句立刻返回，但语句没有全部执行，需要获取结果
    //把sql语句发送给mysql_server ,server 一条条执行，返回结果
    re = mysql_query(&mysql,sql.c_str());
    count = mysql_affected_rows(&mysql);
    if(re != 0){
        cout<<"mysql_query failed!"<<mysql_error(&mysql)<<std::endl;
    }

    //有多个返回结果
    //取下一条结果
    do{
        MYSQL_RES*result= mysql_store_result(&mysql);
        if(result){
            cout<<"mysql_num_rowes="<<mysql_num_rows(result)<<endl;
            mysql_free_result(result);
        }else{//insert update deletet create drop trncate
            //select 出错，有字段，无结果
            if(mysql_field_count(&mysql)>0){
                cout<<"Not retrieve result!"<<mysql_error(&mysql)<<endl;
            }else{
                //等待服务器
                cout<<mysql_affected_rows(&mysql)<<" rows affected!"<<endl;
            }
        }
    }while(mysql_next_result(&mysql) == 0);//0表示有结果

    mysql_close(&mysql);
    mysql_library_end();
    std::cout<<"Mysql 8.0 API"<<endl;
    return 0;
}